package show.me.the.money.accredit.condition;

import java.util.HashMap;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.dom4j.Element;

import show.me.the.money.util.context.Context;
import show.me.the.money.util.exp.ExpRunner;



public class JsonExpCondition implements Condition {
	private static ObjectMapper jsonMapper = new ObjectMapper();
	Element define;
	HashMap<String,Object> data;
	String target;
	
	@SuppressWarnings("unchecked")
	public void setDefine(Element define){
		this.define = define;
		if(define == null){
			return;
		}
		Element exp = define.element("exp");
		Element msg = define.element("errMsg");
		target = define.attributeValue("type");
		String  expText = null;
		if(exp == null){
			expText = define.attributeValue("exp",define.getText()); 
		}
		else{
			expText = exp.getText();
		}
		
		try {
			expText = expText.trim().replaceAll("\'", "\"");
			List lsExp = jsonMapper.readValue(expText,List.class);
			data = new HashMap<String,Object>();
			data.put("exp", lsExp);
			if(msg != null){
				data.put("errMsg",msg.getText());
			}
		} 
		catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
	public Element getDefine() {
		return define;
	}

	public String getMessage() {
		return (String)data.get("errMsg");
	}

	@SuppressWarnings("unchecked")
	public Object run(Context ctx) {
		return ExpRunner.run((List)data.get("exp"), ctx);
	}
	

	public HashMap<String,Object> data() {
		return data;
	}


	public String target() {
		return target;
	}


	public int type() {
		return Condition.EXP;
	}

}
